package top.blueShark.template.controller;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;
import top.blueShark.template.common.Result;
import top.blueShark.template.common.util.Base64ToMultipartFile;
import top.blueShark.template.common.util.StringUtils;
import top.blueShark.template.entity.SysUser;
import top.blueShark.template.entity.dto.SysUserDTO;
import top.blueShark.template.entity.dto.SysUserRequestDTO;
//import top.blueShark.template.entity.dto.UserDTO;
import top.blueShark.template.entity.vo.UserInfoVO;
import top.blueShark.template.service.SysUserService;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 系统用户管理模块-用户管理接口
 */
@RestController
@RequestMapping("/api/system/user")
@Tag(name = "系统用户管理模块", description = "系统用户管理模块")
public class SysUserController {

    private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);

    @Value("${file.upload.dir}")
    private String uploadDir;

    @Value("${file.upload.url-prefix}")
    private String fileUrlPrefix;

    @Resource
    private SysUserService sysUserService;

//    /**
//     * 修改用户信息
//     * */
//    @PutMapping
//    @Operation(summary = "修改用户信息",description = "修改用户信息")
//    public Result updateUserInfo(@RequestBody UserDTO userDTO) {
//        Map<String, Object> result = new HashMap<>();
//        MultipartFile multipartFile = null;
//        try{
//            multipartFile = new Base64ToMultipartFile(userDTO.getBase64Avatar(), userDTO.getUsername() + "-" + System.currentTimeMillis() + "-" + UUID.randomUUID().toString().replace("-",""), "image/jpeg");
//        }catch (Exception e){
//            throw new RuntimeException("文件为空，文件转换错误-"+e.getMessage());
//        }
//        //保存新头像文件
//        String originalFilename = multipartFile.getOriginalFilename();
//        logger.info("originalFilename:"+originalFilename);
//        logger.info(multipartFile.getContentType());
//        String ext = "jpg";
//        String saveName = originalFilename + "." + ext;
//        File userDir = new File(uploadDir, String.valueOf(userDTO.getId()));
//        userDir.mkdirs();
//        File newDest = new File(userDir, saveName);
//        newDest.getParentFile().mkdirs();
//        try {
//            logger.info("目标文件路径：" + newDest.getAbsolutePath());
//            multipartFile.transferTo(newDest);
//        } catch (IOException e) {
//            result.put("code", 2);
//            result.put("message", "文件保存失败: " + e.getMessage());
//            return Result.fail();
//        }
//        // 移除旧头像文件
//        SysUser user = sysUserService.getById(userDTO.getId());
//        String avatarPath = user.getAvatar();
//        if (avatarPath != null) {
//            File oldNewDest = new File(avatarPath);
//            if (oldNewDest.exists()) {
//                oldNewDest.delete();
//            } else {
//                // 头像文件不存在的情况下处理
//                logger.info("头像文件不存在");
//            }
//        } else {
//            // 头像路径为空时的处理
//            logger.info("头像路径为空");
//        }
//        //保存数据库
//        SysUser newUser = new SysUser();
//        BeanUtils.copyProperties(userDTO, newUser);
//        newUser.setAvatar(fileUrlPrefix + userDTO.getId() + "/" + saveName);
//        newUser.setPassword(SaSecureUtil.md5(userDTO.getPassword()));
//        System.out.println(newUser);
//        sysUserService.update(newUser);
//
//        return Result.success();
//    }

    /**
     * 获取用户信息
     * */

    @GetMapping("/info")
    public Result<UserInfoVO> getUserInfo() {
        // 从 Sa-Token 获取当前登录用户ID
        Long userId = StpUtil.getLoginIdAsLong();
        SysUser user = sysUserService.getById(userId);
        List<String> roles = sysUserService.getRoleNamesByUserId(userId);
        // 转为时间戳（毫秒）
        UserInfoVO userInfoVO = new UserInfoVO();
        BeanUtils.copyProperties(user, userInfoVO);
        userInfoVO.setRoles(roles);
        return Result.success(userInfoVO);
    }

    @GetMapping("/list")
    public Map<String, Object> list(SysUserRequestDTO sysUserRequestDTO) {
        List<SysUser> users = sysUserService.getAll(sysUserRequestDTO);
        Map<String, Object> data = new HashMap<>();
        data.put("items", users);
        data.put("total", users.size());

        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", data);
        result.put("error", null);
        result.put("message", "ok");
        return result;
    }

    // 获取用户详情
    @GetMapping("/{id}")
    public Map<String, Object> detail(@PathVariable Long id) {
        SysUser user = sysUserService.getById(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", user);
        result.put("error", null);
        result.put("message", "ok");
        return result;
    }


    /**
     * @更新用户
     * */
    @PutMapping("/{id}")
    public Map<String, Object> update(@PathVariable Long id, @RequestBody SysUserDTO sysUserDTO) {
        /* 先更新数据库信息，如果更新成功-删除历史文件 */
        long userId = StpUtil.getLoginIdAsLong();
        SysUser dbUser = sysUserService.getById(id);
        String dbAvatarUrl = dbUser.getAvatar();
        /* 1、更新数据库 */
        SysUser user = new SysUser();
        BeanUtils.copyProperties(sysUserDTO, user);
        user.setId(id); // 确保将路径中的 id 设置到 user 对象中
        logger.info("Received roles for update: " + user.getRoles()); // 添加日志打印
        logger.info("新的用户信息：{}", user);
        int effect = sysUserService.update(user);

        /* 2、根据是否更新成功-删除历史文件 */
        if (effect > 0){
            if (isValidAvatarUrl(dbAvatarUrl, sysUserDTO.getAvatar())) {
                /* 移除老图片 - 构造物理文件路径 */
                String updateUserId = String.valueOf(id);
                Integer lastIndexOfChar = StringUtils.getLastIndexOfChar(dbAvatarUrl, "/");
                String fileName = StringUtils.substringFromIndex(dbAvatarUrl, lastIndexOfChar);
                String filePath = constructFilePath(updateUserId, fileName);
                try {
                    File file = new File(filePath);
                    if (file.exists()) {
                        boolean delete = file.delete();
                        if (delete) logger.info("用户 [ {} ] 执行更新操作，更新用户 [ {} ]的头像。更新图片地址URL：{}，成功移除历史图片URL：{}",userId, updateUserId,sysUserDTO.getAvatar(),dbAvatarUrl);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", null);
        result.put("error", null);
        result.put("message", "更新成功");
        return result;
    }

    /**
     * 构建文件的物理路径
     */
    private String constructFilePath(String updateUserId, String fileName) {
        return uploadDir + File.separator + updateUserId + File.separator + fileName;
    }
    /**
     * 检查头像 URL 是否有效并与当前头像不同
     */
    private boolean isValidAvatarUrl(String dbAvatarUrl, String newAvatarUrl) {
        return dbAvatarUrl != null && !dbAvatarUrl.isEmpty() && !dbAvatarUrl.equals(newAvatarUrl);
    }

    // 删除用户
    @DeleteMapping("/{id}")
    public Map<String, Object> delete(@PathVariable Long id) {
        sysUserService.delete(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", null);
        result.put("error", null);
        result.put("message", "删除成功");
        return result;
    }

    // 新增用户
    @PostMapping
    public Map<String, Object> add(@RequestBody SysUser user) {
        sysUserService.add(user);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", null);
        result.put("error", null);
        result.put("message", "添加成功");
        return result;
    }

    // 查询用户的角色ID列表
    @GetMapping("/{id}/roles")
    public Map<String, Object> getUserRoles(@PathVariable Long id) {
        List<String> roleIds = sysUserService.getRoleIdsByUserId(id);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", roleIds);
        result.put("error", null);
        result.put("message", "ok");
        return result;
    }

    // 给用户分配角色
    @PostMapping("/{id}/roles")
    public Map<String, Object> assignRoles(@PathVariable Long id, @RequestBody List<String> roleIds) {
        sysUserService.assignRoles(id, roleIds);
        Map<String, Object> result = new HashMap<>();
        result.put("code", 0);
        result.put("data", null);
        result.put("error", null);
        result.put("message", "分配成功");
        return result;
    }

}